import inspect
from pathlib import Path

def getpyfile(direction):

    p = Path(direction)
    if not p.is_dir():
        raise ValueError('given direction must be a file direction')
    for item in p.iterdir():
        if item.is_file() and item.name.endswith('.py'):
            print(item.absolute())
        if item.is_dir():
            getpyfile(item)

#实现一个可以找出给定文件夹里py文件的类，并且这是一个可以迭代的类
class TypeCheck:
    def __init__(self,name):
        self.name = name

    def __get__(self, instance, owner):
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        path = Path(value)
        if not path.is_dir() or not path.exists() :
            print('No such direction')
            value = None    #路径不存在直接将路径值置为None，避免相关异常抛出
        instance.__dict__[self.name] = value

class DataInject:
    def __init__(self,cls):
        self.cls = cls
        sig = inspect.signature(cls)
        params = sig.parameters
        for name,param in params.items():
            setattr(cls,name,TypeCheck(name))   #init里实现功能代码，而不是实例值的传递，是不是不优雅？？

    def __call__(self, *args, **kwargs):
        return self.cls(*args,**kwargs)

@DataInject
class ShowPyFiles:
    def __init__(self,direction):
        self.direction = direction
        self.filelists = []

    def find(self):
        if self.direction is not None: #路径不存在，不会有任何文件结果显示
            p = Path(self.direction)
            for item in p.iterdir():
                if item.is_file() and item.name.endswith('.py'):
                    self.filelists.append(item)
                    yield item
                if item.is_dir():
                    self.direction = item
                    res = self.find()
                    yield from res

    def __iter__(self):
        yield from self.find() #或者 yield from self.filelists

    def __len__(self):
        return len(self.filelists)

d =  ShowPyFiles(r'C:\Users\28625\Desktop\新建文件夹')

for z in d:print(z)
print(len(d))


"""
找出目录下以.py结尾的文件完成的不错
第二题可以更简化些
"""

